/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 *
 * @description 开启红点的链接
 */

import { getTransferData, openInvoiceList } from '@/services/Finance/approval';
import { getCloudCallTemplateList } from '@/services/cloudCall';
import { getStationInvoiceList, getWkdInvoiceList } from '@/services/finance_receipt';
import { getInfoVerifyList, getTableList } from '@/services/operatorManagement';
import { getSmsList } from '@/services/sms/examine';
import { getWaitForApproveTemplate } from '@/services/sms/specialTmp';
import { getTemplateAuditList } from '@/services/templateAudit';
import { isArray } from 'lodash';
import moment from 'moment';
import RedPointRequestCache, { Refresh, Request, RequestOptions } from './cache';

interface EnableRedPointItem {
  key: string;
  label: string;
  request: (r: Refresh, o: RequestOptions) => Promise<boolean>;
}

type EnableRedPointCurrent = EnableRedPointItem[];
interface EnableRedPointMap {
  [k: string]: EnableRedPointCurrent;
}

/**
 *
 * @description 补充请求日期，默认为近一个月的
 * @returns
 */
function patchDataWithDate(opts: any) {
  const [s_date, e_date] = [moment().subtract(30, 'days'), moment()].map((item) =>
    item.format('YYYY-MM-DD'),
  );
  return { ...opts, s_date, e_date };
}

/**
 *
 * @description 统一处理数据，有待处理数据，返回true，否则为false;
 * 注意res如果是数组，则只要有一组有待处理数据，则返回true；
 * @param res
 * @returns
 */
export function checkData(res: any): boolean {
  if (!isArray(res)) {
    // 数据格式不统一
    const { dataList, data = dataList } = (res || {}) as any;
    const { result, list = result || data } = (data || {}) as any;
    return isArray(list) && list.length > 0;
  }
  return res.some((item) => checkData(item));
}

const requestCache = new RedPointRequestCache();

/**
 *
 * @description 检查触发refresh
 * @param request
 * @param fromRedDot
 * @param res
 * @returns
 */
export function checkAndTriggerRefresh(request: any, fromRedDot?: boolean) {
  return (res: any) => {
    requestCache.refresh(request, !fromRedDot);
    return res;
  };
}

/**
 *
 * @description 触发请求，并设置缓存refresh;
 * @param request
 * @param opts
 * @param refresh
 * @returns
 */
function triggerRequest(request: Request, opts: any) {
  return (refresh: Refresh, refreshOptions: RequestOptions) => {
    requestCache.set(request, refresh, refreshOptions);
    return request(opts, true).then(checkData);
  };
}

export const enableRedPointMap: EnableRedPointMap = {
  // 财务管理
  // 对公转账申请审核
  '/f/finance/approval': [
    {
      key: '0',
      label: '网点后台',
      request: triggerRequest(
        getTransferData,
        patchDataWithDate({
          pageSize: 1,
          type: 0,
          page: 1,
        }),
      ),
    },
    {
      key: '1',
      label: '开放平台',
      request: triggerRequest(openInvoiceList, {
        status: 1,
        page: 1,
        size: 1,
        pay_type: 3,
      }),
    },
  ],
  // 开票申请审核
  '/f/finance/wkdInvoice': [
    {
      key: '0',
      label: '微快递/全寄开票审核',
      request: triggerRequest(
        getWkdInvoiceList,
        patchDataWithDate({
          page: 1,
          source: '',
          pageSize: 1,
          status: 1,
        }),
      ),
    },
    {
      key: '1',
      label: '网点开票审核',
      request: (refresh, refreshOptions) => {
        return Promise.all(
          [1, 2].map((company_type) =>
            triggerRequest(
              getStationInvoiceList,
              patchDataWithDate({
                page: 1,
                pageSize: 1,
                company_type,
                invoice_type: 0,
                type: 0,
              }),
            )(refresh, refreshOptions),
          ),
        ).then((res) => res.some((item) => !!item));
      },
    },
    {
      key: '2',
      label: '聚单客开票审核',
      request: triggerRequest(
        getWkdInvoiceList,
        patchDataWithDate({
          page: 1,
          source: 'jdk',
          pageSize: 1,
          status: 1,
        }),
      ),
    },
    {
      key: '3',
      label: '开放平台开票审核待开票数据',
      request: triggerRequest(openInvoiceList, {
        status_invoice: 0,
        type: '',
        page: 1,
        size: 1,
      }),
    },
  ],

  // 短信/云呼管理
  // 短信模板审核
  '/f/sms/dispatchTmp': [
    {
      key: '0',
      label: '待审核模板',
      request: triggerRequest(getTemplateAuditList, {
        page_num: 1,
        part: '1',
        state: 'indeterminate',
      } as any),
    },
  ],
  // 短信审核
  '/f/sms/examine': [
    {
      key: '0',
      label: '待审核短信',
      request: triggerRequest(getSmsList, {
        status: 'wait',
        page_num: 1,
        page_size: 1,
      }),
    },
  ],
  // 云呼模板审核
  '/f/sms/cloudTmp': [
    {
      key: '0',
      label: '待审核',
      request: triggerRequest(getCloudCallTemplateList, {
        page_num: 1,
        type: 1,
        pageSize: 1,
      } as any),
    },
  ],
  // 特定模板审核
  '/f/sms/specialTmp': [
    {
      key: '0',
      label: '超限模板审核',
      request: triggerRequest(getWaitForApproveTemplate, {
        page: 1,
        limit: 1,
      }),
    },
  ],

  // 驿站站点管理
  // 驿站经营信息审核
  '/f/yz/infoVerify': [
    {
      key: '0',
      label: '待审核',
      request: triggerRequest(getInfoVerifyList, {
        page: 1,
        limit: 1,
        type: 1,
      }),
    },
  ],
  // 驿站基础信息审核
  '/f/yz/addressVerify': [
    {
      key: '0',
      label: '待审核',
      request: triggerRequest(getTableList, {}),
    },
  ],
};
